﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using FineUI;
using ZHDJ.Core.Caching;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;
using ZHDJ.WebPage.Picker;

namespace ZHDJ.Web.App.Share.Picker
{
    public partial class BranchMultiplePicker : PickerPageBase
    {
        /// <summary>
        /// 
        /// </summary>
        public string BranchID
        {
            get { return Request.QueryString["BranchID"]??""; }
        }
        /// <summary>
        /// 已经选择的用户
        /// </summary>
        public List<string> selectBranchs
        {
            get
            {
                return string.IsNullOrEmpty(hdSelectBranchs.Text) ? new List<string>() :
                  hdSelectBranchs.Text.Split(',').ToList();
            }
            set
            {
                if (value != null && value.Count > 0)
                {
                    hdSelectBranchs.Text = string.Join(",", value.ToArray());
                    hdSelectBranchIDs.Text =
                        string.Join(",", (from u in value select u.Split('|')[0]).ToArray());
                }
                else
                {
                    hdSelectBranchIDs.Text = hdSelectBranchs.Text = "";
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTree();
                BindData();
                LoadData();
            }
        }

        #region 数据操作
        private void BindData()
        {
            //绑定已选择的值
            var selected = SelectValue;
            if (selected.Count < 1)
                return;
            var selectBranch = DB.PartyOrgBranchs.Where(a => selected.Contains(a.BranchID));
            //if (selectedUser.Count() < 1)
            //    return;
            var d = from u in selectBranch select u.BranchID + "|" + u.BranchName;
            selectBranchs = d.ToList();
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
        }
        private void LoadData()
        {
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            BindTreeCheck();
            BindGridSelect();
        }

        private int Level = 0;
        private void BindTree()
        {

            TreeControlBusiness tree = new TreeControlBusiness("BranchID", "ParentBranchID", "BranchName", true, CacheKeys.Cache_Branch_Tree_Picker);
            tree.EnableCheckEvent = true;
            tree.IsAllCheckBox = true;
            tree.BindTreeBranch(TreeBranch);
            if (!string.IsNullOrEmpty(BranchID))
            {
                var n = TreeBranch.FindNode(BranchID);
                TreeBranch.Nodes.Clear();
                if (n != null)
                    TreeBranch.Nodes.Add(n);
            }
            if (TreeBranch.Nodes.Count > 0)
            {
                //展开第一层
                TreeBranch.Nodes[0].Expanded = true;
            }
            //取消所有选中（避免缓存）
            TreeNode[] nodes = TreeBranch.GetCheckedNodes();
            if (nodes.Length > 0)
            {
                
                //取消选中
                foreach (TreeNode node in nodes)
                {
                    node.Checked = false;
                }
            }
        }

       
        private void BindTreeCheck()
        {
            TreeBranch.UncheckAllNodes();
            var ids = hdSelectBranchIDs.Text.Split(',');
            foreach (var item in ids)
            {
                var node = TreeBranch.FindNode(item);
                if (node != null)
                {
                    TreeBranch.FindNode(item).Checked = true;
                }
            }
        }
        /// <summary>
        /// 绑定已选择的用户表
        /// </summary>
        private void BindGridSelect()
        {

            GridSelect.DataSource = InitselectBranchsTable();
            GridSelect.DataBind();

        }

        /// <summary>
        /// 初始化已选择表格
        /// </summary>
        /// <returns></returns>
        private DataTable InitselectBranchsTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BranchID", typeof(string));
            dt.Columns.Add("BranchName", typeof(string));
            dt.Columns["BranchID"].DefaultValue = "";
            dt.Columns["BranchName"].DefaultValue = "";
            foreach (var item in selectBranchs)
            {
                var dr = dt.NewRow();
                dr["BranchID"] = item.Split('|')[0];
                dr["BranchName"] = item.Split('|')[1];
                dt.Rows.Add(dr);
            }
            
            return dt;
        }

        #endregion

        #region 事件
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            if (selectBranchs == null || selectBranchs.Count < 1)
            {
                Alert.Show("请选择组织！", String.Empty);
                return;
            }
            List<string> value = (from u in selectBranchs select u.Split('|')[0]).ToList();
            List<string> text = (from u in selectBranchs select u.Split('|')[1]).ToList();
            ReturnValue(string.Join(",", value.ToArray()), string.Join(",", text.ToArray()));
        }


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            // BindGrid();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            //BindGrid();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void TreeBranch_NodeCheck(object sender, TreeCheckEventArgs e)
        {
            //获取选中集合
            TreeNode[] nodes = TreeBranch.GetCheckedNodes();
            selectBranchs = new List<string>();
            var listcheck=new List<string>();
            foreach (TreeNode node in nodes)
            {
                listcheck.Add(node.NodeID + "|" + node.Text);
            }
            selectBranchs = listcheck;
            LoadData();
        }
           
           
           
        

        /// <summary>
        /// 移除选中的人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemoveSelectBranch_Click(object sender, EventArgs e)
        {
            var list = new List<string>();
            foreach (int rowIndex in GridSelect.SelectedRowIndexArray)
            {
                list.Add(Convert.ToString(GridSelect.DataKeys[rowIndex][0]) + "|" + Convert.ToString(GridSelect.DataKeys[rowIndex][1]));

            }
            selectBranchs = selectBranchs.Except(list).ToList();
            LoadData();
        }

        /// <summary>
        /// 移除所有的人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemoveAllBranch_Click(object sender, EventArgs e)
        {
            selectBranchs = new List<string>();
            LoadData();
        }
        protected void GridSelect_RowCommand(object sender, GridCommandEventArgs e)
        {
            string userID = ControlBusiness.GetSelectedDataKeyID(GridSelect);
            string userName = ControlBusiness.GetSelectedDataKey(GridSelect, 1);
            if (e.CommandName == "Remove")
            {
                var list = new List<string>() { userID + "|" + userName };
                selectBranchs = selectBranchs.Except(list).ToList();
                LoadData();
            }

        }
        #endregion
    }
}